import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { UserInfo } from '@/api/auth/types';
import { login as loginApi, getUserInfo, logout as logoutApi } from '@/api/auth';
import type { LoginRequest } from '@/api/auth/types';

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '');
  const userInfo = ref<UserInfo | null>(null);
  const rememberMe = ref(false);

  // 初始化状态，从localStorage获取保存的信息
  const initStore = () => {
    const savedToken = localStorage.getItem('token');
    const savedUserInfo = localStorage.getItem('userInfo');
    const savedRememberMe = localStorage.getItem('rememberMe');

    if (savedToken) token.value = savedToken;
    if (savedUserInfo) userInfo.value = JSON.parse(savedUserInfo);
    if (savedRememberMe) rememberMe.value = savedRememberMe === 'true';
  };

  // 设置token
  const setToken = (newToken: string) => {
    token.value = newToken;
    localStorage.setItem('token', newToken);
  };

  // 设置用户信息
  const setUserInfo = (info: UserInfo) => {
    userInfo.value = info;
    localStorage.setItem('userInfo', JSON.stringify(info));
  };

  // 设置记住我状态
  const setRememberMe = (status: boolean) => {
    rememberMe.value = status;
    localStorage.setItem('rememberMe', String(status));
  };

  // 清除登录状态
  const clearLoginState = () => {
    token.value = '';
    userInfo.value = null;
    rememberMe.value = false;
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    localStorage.removeItem('rememberMe');
  };

  // 判断是否已登录
  const isLoggedIn = () => {
    return !!token.value;
  };

  const login = async (loginData: LoginRequest) => {
    try {
      const response = await loginApi(loginData);
      setToken(response.data.token);
      setUserInfo(response.data.user);
      return true;
    } catch (error) {
      return false;
    }
  };

  const logout = async () => {
    try {
      await logoutApi();
      clearLoginState();
      return true;
    } catch (error) {
      return false;
    }
  };

  const fetchUserInfo = async () => {
    try {
      const response = await getUserInfo();
      setUserInfo(response.data);
      return true;
    } catch (error) {
      return false;
    }
  };

  // 初始化store
  initStore();

  return {
    token,
    userInfo,
    rememberMe,
    setToken,
    setUserInfo,
    setRememberMe,
    clearLoginState,
    isLoggedIn,
    login,
    logout,
    fetchUserInfo
  };
});
